import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

/**
 * Created by KaiseRR on 26.02.15.
 */
public class ServerThread extends Thread {
    private MessageCenter messageCenter;
    private MessageSender sender;
    private InputStream in;
    private OutputStream out;
    private MessageReceiver receiver;
    private static SiLabsValuesReader siLabsReader;

    public ServerThread(Socket socket, SiLabsValuesReader siLabsReader) throws IOException {
        messageCenter = new MessageCenter(socket.getInetAddress().getHostName());
        in = socket.getInputStream();
        out = socket.getOutputStream();
        sender = new MessageSender(out, messageCenter);
        receiver = new MessageReceiver(in, messageCenter);
        this.siLabsReader = siLabsReader;
        this.siLabsReader.addMessageCenter(messageCenter);
    }

    public void run() {
        try {
            boolean isWorking = true;
            while (isWorking) {

                if (sender.isStopped() || receiver.isStopped() || siLabsReader.isStopped()) {
                    isWorking = false;
                    continue;
                }
                if (!siLabsReader.isAlive() && !siLabsReader.isStopped()) {
                    siLabsReader.start();
                }
                if (!sender.isAlive() && !sender.isStopped()) {
                    sender.start();
                }
                if (!receiver.isAlive() && !receiver.isStopped()) {
                    receiver.start();
                }
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        } catch (Exception e) {
            if (sender != null && !sender.isStopped())
                sender.stopThread();
            if (receiver != null && !receiver.isStopped())
                receiver.stopThread();
            if (!siLabsReader.isAlive() && !siLabsReader.isStopped())
                siLabsReader.stopThread();
            if (in != null) { try { in.close(); } catch (IOException e1) { e1.printStackTrace(); } }
            if (out != null) { try { in.close(); } catch (IOException e1) { e1.printStackTrace(); } }
            e.printStackTrace();
        }
    }
}
